<template>
  <div id="seal">
    <div class="add_seal">
      <el-button icon="iconfont icon-jiufuqianbaoicon06" size="mini" class="exportBtn add" @click="addSeal">
        新增印章
      </el-button>
    </div>
    <div class="list-container">
      <div class="tables">
        <!-- TODO: 如果优化此处表格需要重新写 ps:封装的表格存在问题 -->
        <element-table
          :tableHeader="header"
          :interface="Interface"
          @operateClick="operateClick"
          @checkImg="checkImg"
          ref="sealtable"
        ></element-table>
      </div>
    </div>
    <el-dialog
      width="550px"
      class="sealdialog"
      v-if="sealVisible"
      :center="true"
      :close-on-click-modal="false"
      :title="title"
      :before-close="closeDialog"
      :visible.sync="sealVisible"
    >
      <el-form ref="form" class="infoForm" label-width="100px">
        <el-form-item label="印章名称:" :required="true">
          <el-input v-model.trim="sealName" placeholder="请输入印章名称" size="small" style="width: 220px"> </el-input>
        </el-form-item>
        <el-form-item label="印章类型:" :required="true" v-if="title === '新增印章'">
          <el-radio-group v-model.trim="sealType">
            <el-radio :label="1">企业章</el-radio>
            <el-radio :label="2">法人或代理人章</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="认证信息 :">
          <el-button size="mini" class="exportBtn sealBtn" @click="addInvoicing"> 选择开票信息 </el-button>
        </el-form-item>
        <el-form-item label="印章授权书 :">
          <el-button size="mini" class="exportBtn sealBtn" @click="upload"> 上传授权书 </el-button>
          <span class="sealText" @click="checkExample">示例图</span>
          <span class="sealText" @click="downLoad">下载模板</span>
          <div>
            <el-upload
              class="upload-demo"
              :file-list="filelist"
              action
              :show-file-list="false"
              :auto-upload="false"
              :on-change="getFile"
              accept=".doc,.docx"
            >
              <template slot="trigger">
                <div ref="sealUpload"></div>
              </template>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="印章制作 :">
          <el-button size="mini" class="exportBtn sealBtn" @click="onlineProduction"> 在线制作 </el-button>
        </el-form-item>
      </el-form>
      <div class="" style="margin-top: 20px" v-if="title === '新增印章'">
        <el-checkbox v-model.trim="checked">
          <span style="color: #333">我已阅读</span>
          <span style="color: #fa7355">《电子印章授权协议》</span>
          <span style="color: #333">，并授权给该部门的投标人员使用印章</span>
        </el-checkbox>
      </div>
      <dialog-footer-button @saveName="saveName" @close="close" v-if="title === '新增印章'"></dialog-footer-button>
      <dialog-footer-button @saveName="updateSeal" @close="close" v-else></dialog-footer-button>
    </el-dialog>
    <el-dialog
      :width="sealType === 1 ? '850px' : '620px'"
      class="onlinedialog"
      v-if="onlineVisible"
      :center="true"
      :close-on-click-modal="false"
      title="印章在线制作"
      :before-close="closeDialog"
      :visible.sync="onlineVisible"
    >
      <div class="online_seal">
        <div class="online_left">
          <el-form ref="form" class="infoForm" label-width="110px" v-if="sealType === 1">
            <el-form-item label="公司名称:">
              <el-input v-model.trim="companyName" size="small" style="width: 220px" disabled class="companyinput">
              </el-input>
            </el-form-item>
            <el-form-item label="字体大小:">
              <el-button
                :class="{ active: fontSize === '1' }"
                size="medium"
                class="fontBtn"
                @click="fontSizeChange('大')"
              >
                大
              </el-button>
              <el-button
                size="small"
                :class="{ active: fontSize === '2' }"
                class="fontBtn"
                @click="fontSizeChange('中')"
              >
                中
              </el-button>
              <el-button
                size="mini"
                :class="{ active: fontSize === '3' }"
                class="fontBtn"
                @click="fontSizeChange('小')"
              >
                小
              </el-button>
            </el-form-item>
            <el-form-item label="抬头文字:">
              <el-input
                v-model.trim="companylookup"
                placeholder="可不写，或写合同章或公章"
                size="small"
                style="width: 220px"
              >
              </el-input>
            </el-form-item>
            <el-form-item label="营业执照编号:">
              <el-input v-model.trim="companyNo" size="small" style="width: 220px"> </el-input>
            </el-form-item>
            <el-form-item label="中心图案:">
              <el-radio-group v-model.trim="showpattern">
                <el-radio label="1">显示</el-radio>
                <el-radio label="0">不显示</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="在线预览:">
              <el-button size="mini" class="exportBtn sealBtn" @click="checkSeal"> 点击预览 </el-button>
            </el-form-item>
          </el-form>
          <el-form ref="form" class="infoForm" label-width="80px" v-else>
            <el-form-item label="用户名称:">
              <el-input v-model.trim="companyName" size="small"> </el-input>
            </el-form-item>
            <el-form-item label="在线预览:">
              <el-button size="mini" class="exportBtn sealBtn" @click="checkSeal"> 点击预览 </el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="online_right">
          <el-form ref="form" class="infoForm" label-width="80px">
            <el-form-item label="印章预览:" v-if="sealType === 1">
              <el-image style="width: 300px; height: 300px" :src="sealurl" v-if="sealurl"></el-image>
            </el-form-item>
            <el-form-item label="印章预览:" v-else>
              <el-image style="width: 150px; height: 150px" :src="sealurl" v-if="sealurl"></el-image>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <dialog-footer-button @saveName="saveName('制作印章')" @close="sealClose"></dialog-footer-button>
    </el-dialog>
    <el-dialog
      width="591px"
      class="exampledialog"
      v-if="userVisible"
      :center="true"
      :close-on-click-modal="false"
      title="查看关联用户"
      :before-close="closeDialog"
      :visible.sync="userVisible"
    >
      <div class="checkuser">
        <el-button icon="iconfont icon-jiufuqianbaoicon06" size="mini" class="exportBtn add" @click="addUser">
          新增关联用户
        </el-button>
      </div>
      <div style="height: 300px" id="user_box">
        <element-table
          key="userTable"
          :tableHeader="userheader"
          :interface="userInterface"
          :isHavePag="false"
          @operateClick="delUser"
          ref="usertable"
        >
        </element-table>
      </div>
    </el-dialog>
    <el-dialog
      width="1200px"
      class="exampledialog"
      v-if="sealUserVisible"
      :center="true"
      :close-on-click-modal="false"
      title="选择关联用户"
      :before-close="closeDialog"
      :visible.sync="sealUserVisible"
    >
      <seal-user-select :sealid="userInterface.data.sealId" @close="sealUserClose"></seal-user-select>
    </el-dialog>
    <el-image-viewer style="z-index: 99999" v-if="showViewer" :on-close="viewerClose" :url-list="stencilUrl" />
  </div>
</template>

<script>
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
import DialogFooterButton from '../../../components/dialogFooterButton.vue'
import ElementTable from '../../../components/ElementTable.vue'
import SealUserSelect from './sealUserSelect.vue'
export default {
  components: { ElementTable, DialogFooterButton, ElImageViewer, SealUserSelect },
  data() {
    return {
      showViewer: false,
      exampUrl: '',
      stencilUrl: [],
      filelist: [],
      fontSize: '1',
      Interface: {
        url: '/api/getSealList',
        method: 'post',
        data: {
          createBy: '',
          createTime: '',
          page: 1,
          size: 15
        }
      },
      title: '',
      checked: false,
      sealName: '',
      sealurl: '',
      sealBase64: '',
      powerBase64: '',
      sealType: 1,
      showpattern: '1',
      companylookup: '',
      companyNo: '',
      companyName: localStorage.getItem('enterpriseName'),
      userVisible: false,
      sealVisible: false,
      sealUserVisible: false,
      onlineVisible: false,
      header: [
        {
          label: '印章名称',
          prop: 'sealName'
        },
        {
          label: '印章样式',
          prop: 'sealImgUrl',
          isImg: true
        },
        {
          label: '认证信息(开票公司名称)',
          prop: 'rise',
          width: '300px'
        },
        {
          label: '创建时间',
          prop: 'createTime'
        },
        {
          label: '状态',
          prop: 'state'
        },
        {
          label: '操作',
          isBtn: true,
          width: '250px',
          fixed: 'right',
          prop: '',
          btnItem: [
            { label: '查看关联用户', className: 'xg czBtn' },
            { label: '编辑', className: 'xg czBtn' }
          ]
        }
      ],
      userheader: [
        { label: '用户名', prop: 'userName' },
        { label: '手机号', prop: 'phone' },
        { label: '操作', isBtn: true, prop: '', btnItem: [{ label: '删除', className: 'sc czBtn' }] }
      ],
      userInterface: {
        method: 'post',
        url: '/api/queryUserSeal',
        data: {
          sealId: ''
        }
      }
    }
  },
  mounted() {},
  methods: {
    // 修改印章
    updateSeal() {
      let power64 = this.powerBase64.split(',')[1]
      this.$https({
        url: '/api/updateSeal',
        method: 'post',
        data: {
          id: this.userInterface.data.sealId,
          invoiceHeaderId: 1,
          powerOfAttorney: power64,
          rise: '越码科技',
          sealImge: this.sealBase64,
          sealName: this.sealName
        }
      }).then(res => {
        if (res.code === 0) {
          this.$message.success('修改成功')
          this.close()
          this.$refs.sealtable.getData()
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    checkImg(url) {
      this.stencilUrl.push(url)
      this.showViewer = true
    },
    sealUserClose() {
      this.$refs.usertable.getData()
      this.sealUserVisible = false
    },
    addUser() {
      this.sealUserVisible = true
    },
    // 删除印章关联用户
    delUser(label, scope) {
      this.$confirm('是否删除关联用户！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$https({
            method: 'post',
            url: '/api/deleteUserSeal',
            data: {
              id: scope.id
            }
          }).then(res => {
            if (res.code === 0) {
              this.$message.success('删除成功')
              this.$refs.usertable.getData()
            } else {
              this.$message.error(res.msg)
            }
          })
        })
        .catch(() => {})
    },
    operateClick(label, scope) {
      if (label === '查看关联用户') {
        this.userInterface.data.sealId = scope.id
        this.userVisible = true
      } else if (label === '编辑') {
        this.title = '修改印章'
        this.sealVisible = true
        this.userInterface.data.sealId = scope.id
        this.$https({
          method: 'post',
          url: '/api/querySeal',
          data: {
            id: scope.id
          }
        })
          .then(res => {
            if (res.code === 0) {
              this.getUrl()
              this.sealType = res.data.sealType
              this.sealName = res.data.sealName
            } else {
              this.$message.error(res.msg)
            }
          })
          .catch(err => {
            console.log(err)
          })
      } else if (label === '停用') {
        this.sealState(false, scope.id)
      } else if (label === '启用') {
        this.sealState(true, scope.id)
      }
    },

    sealState(val, id) {
      this.$https({
        url: '/api/updateSealState',
        method: 'post',
        data: {
          id: id,
          state: val
        }
      })
        .then(res => {
          if (res.code === 0) {
            this.$message.success('操作成功')
            this.$refs.sealtable.getData()
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    viewerClose() {
      this.showViewer = false
      this.stencilUrl = []
    },
    // 印章授权书文件上传
    getFile(data, val) {
      let file = data.raw
      var testmsg = data.name.substring(file.name.lastIndexOf('.') + 1)
      const extension3 = testmsg === 'doc' || testmsg === 'docx'
      if (!extension3) {
        this.$message.error('上传失败,上传文件类型必须是doc或者是docx')
      }
      var isLt2M = file.size / 1024 / 1024 < 20
      if (!isLt2M) {
        this.$message.error('上传失败,文件太大咯，上传的图片大小不能超过 20MB!')
      }
      if (extension3 && isLt2M) {
        // 调用转方法base64
        this.getBase64(data.raw).then(res => {
          this.powerBase64 = res
          this.$message.success('文件上传成功')
          val.forEach(element => {
            this.filelist.push({
              name: element.name
            })
          })
        })
      }
    },
    // 转base64码
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        let reader = new FileReader()
        let imgResult = ''
        reader.readAsDataURL(file)
        reader.onload = function () {
          imgResult = reader.result
        }
        reader.onerror = function (error) {
          reject(error)
        }
        reader.onloadend = function () {
          resolve(imgResult)
        }
      })
    },
    // 印章字体大小
    fontSizeChange(val) {
      if (val === '大') {
        this.fontSize = '1'
      } else if (val === '中') {
        this.fontSize = '2'
      } else {
        this.fontSize = '3'
      }
    },
    checkSeal() {
      let flag = false
      if (this.sealType === 2 && !this.companyName) {
        this.$message.error('请输入用户名称')
        return false
      }
      if (this.companyNo.length > 18) {
        this.$message.error('请输入小于18位的营业执照')
        return false
      }
      if (this.companylookup) {
        if (this.companylookup.length == 2 || this.companylookup.length == 3) {
          flag = true
        } else {
          this.$message.error('抬头文字，字数限制为两字或三字')
          flag = false
        }
      } else {
        flag = true
      }
      if (flag) {
        this.$https({
          method: 'post',
          url: '/api/getSealImage',
          data: {
            centerName: this.companylookup,
            enterpriseCode: this.companyNo,
            message: this.companyName,
            sealType: this.sealType,
            show: this.showpattern === '1' ? true : false,
            type: this.fontSize
          }
        })
          .then(res => {
            if (res.code === 0) {
              this.sealBase64 = res.data
              this.sealurl = 'data:image/png;base64,' + res.data
            } else {
              this.$message.error(res.msg)
            }
          })
          .catch(err => {
            console.log(err)
          })
      }
    },
    onlineProduction() {
      this.onlineVisible = true
    },
    checkExample() {
      this.showViewer = true
    },
    // 下载授权书模板
    downLoad() {
      location.href = this.exampUrl
    },
    // 触发上传
    upload() {
      this.$refs.sealUpload.click()
    },

    saveName(val) {
      if (val === '制作印章') {
        this.checkSeal()
        if (this.companyNo.length > 18) {
          return false
        }
        this.sealClose('2')
      } else {
        if (this.sealName === '') {
          this.$message.error('印章名称不能为空')
        } else if (!this.sealType) {
          this.$message.error('请选择印章类型')
        } else if (this.powerBase64 === '') {
          this.$message.error('请上传印章授权书')
        } else if (this.sealBase64 === '') {
          this.$message.error('请制作印章')
        } else if (!this.checked) {
          this.$message.error('请阅读并勾选下方协议')
        } else {
          let power64 = this.powerBase64.split(',')[1]
          this.$https({
            method: 'post',
            url: '/api/addSeal',
            data: {
              invoiceHeaderId: 1,
              powerOfAttorney: power64,
              rise: '越码科技',
              sealImge: this.sealBase64,
              sealName: this.sealName,
              sealType: this.sealType
            }
          })
            .then(res => {
              if (res.code === 0) {
                this.close()
                this.$message.success('操作成功')
              } else {
                this.$message.error(res.msg)
              }
            })
            .catch(err => {
              console.log(err)
            })
        }
      }
    },
    sealClose(val) {
      if (val) {
        this.onlineVisible = false
      } else {
        this.$confirm('是否取消，取消后印章不会保存', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.onlineVisible = false
            this.sealurl = ''
            this.sealBase64 = ''
          })
          .catch(() => {})
      }
    },
    close() {
      this.powerBase64 = ''
      this.sealImge = ''
      this.sealName = ''
      this.sealVisible = false
    },
    addInvoicing() {},
    getUrl() {
      this.$https({
        method: 'post',
        url: '/api/queryUrl'
      })
        .then(res => {
          if (res.code === 0) {
            this.stencilUrl.push(res.data.stencilUrl)
            this.exampUrl = res.data.exampleUrl
          } else {
            this.$message.error(res.msg)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },

    addSeal() {
      this.sealVisible = true
      this.title = '新增印章'
      this.getUrl()
    },
    closeDialog(done) {
      done()
    }
  },
  watch: {
    sealType() {
      if (this.sealType === 1) {
        this.companyName = localStorage.getItem('enterpriseName')
      } else {
        this.companyName = ''
      }
      return
    }
  }
}
</script>
<style lang="less" scoped>
#user_box {
  /deep/ #el_tablelist {
    height: 100%;
  }
}
.checkuser {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}
#seal {
  height: 100%;
  .add_seal {
    display: flex;
    justify-content: flex-end;
    padding: 16px;
  }
  .list-container {
    height: calc(100% - 104px);
    padding: 0px 16px 40px 16px;
    .tables {
      height: 100%;
    }
  }
  .sealBtn {
    width: 180px;
  }
  .add {
    display: flex;
    align-items: center;
    justify-content: space-evenly;
    width: 114px;
  }
  /deep/ .el-form-item {
    margin-bottom: 12px;
  }
  .sealText {
    margin-left: 10px;
    color: #fa6c50;
    cursor: pointer;
  }
  .companyinput {
    /deep/ .el-input__inner {
      background-color: #d6d6d6 !important;
    }
  }
  .fontBtn {
    color: #fa7355 !important;
    background-color: #fff;
    border: 1px solid #fa7355 !important;
  }
  .active {
    color: #fff !important;
    background-color: #fa7355;
    border: 1px solid #fa7355 !important;
  }
  .online_seal {
    display: flex;
    .online_left {
      height: auto;
      padding-right: 30px;
      border-right: 1px dashed #ccc;
    }
    .online_right {
      height: auto;
      padding-left: 30px;
    }
  }
  /deep/ .el-upload {
    display: none;
  }
}
</style>
